package org.simpatia.service.jvm.runtime;

import org.simpatia.Context;
import org.simpatia.Module;
import org.simpatia.Service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class JVMRuntimeServiceImpl implements Service<Void, JVMRuntimeService>, JVMRuntimeService {
    private Context context;

    public void activate(String name, Void configuration, Context context) {
        this.context = context;
    }

    public void destroy() {
        context = null;
    }

    public JVMRuntimeService getRESTInterface() {
        return this;
    }

    public void registerService(String serviceName, Module module) {
    }

    public void unregisterService(String serviceName) {
    }

    public List<ClassInfo> getClasses() {
        if(context.getInstrumentation() == null) {
            throw new RuntimeException("Instrumentation is not available");
        }

        List<ClassInfo> result = new ArrayList<ClassInfo>();
        Class[] classes = context.getInstrumentation().getAllLoadedClasses();
        for(Class clazz : classes) {
            ClassInfo classInfo = new ClassInfo();
            classInfo.setClassName(clazz.getName());
            if(clazz.getProtectionDomain().getCodeSource() != null &&
                    clazz.getProtectionDomain().getCodeSource().getLocation() != null) {
                classInfo.setLocation(clazz.getProtectionDomain().getCodeSource().getLocation().toString());
            }

            result.add(classInfo);
        }

        Collections.sort(result, new Comparator<ClassInfo>() {
            public int compare(ClassInfo o1, ClassInfo o2) {
                return o1.getClassName().compareTo(o2.getClassName());
            }
        });

        return result;
    }
}
